<?php
namespace app\controllers;

use app\common\ApiResponse;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\Cors;
use yii\filters\RateLimiter;

/**
 * Api请求响应基类
 * 定义相关的认证方式、速率等
 */
class ApiBaseController extends \yii\rest\Controller
{


    public function behaviors(): array
    {
        $behaviors = parent::behaviors();

        // 配置跨域
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Methods' => ['*'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
            ]
        ];

        // 配置认证
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                //配置API接口认证方式
                QueryParamAuth::class, // url中追加access-token=XXX
                HttpBearerAuth::class,  // Header 中追加Key：Authorization，Value：Bearer XXXX
            ],
        ];
		
		// 配置签名
        $behaviors['signAuth'] = [
            'class' => ApiAuth::class,
            'optional' => ['sign','get-version']
        ];

        // 关闭速率限制
        $behaviors['rateLimiter']['enableRateLimitHeaders'] = false;

        return $behaviors;
    }

    /**
     * @var ApiResponse
     */
    protected ApiResponse $_api;

    /**
     * @param $id
     * @param $module
     * @param $config
     */
    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->_api = new ApiResponse();
    }

    public function actionIndex(): array
    {
        return $this->_api->success([
            'authMethods' => [
                'HttpBearerAuth',
                'QueryParamAuth',
            ]
        ]);
    }



}